Find the Sum of Natural Numbers
Course- R Programming >
Source Code
# Program to find the sum of
# natural numbers upto n
# where n is provided by user
# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
if(num < 0) {
print("Enter a positive number")
} else {
sum = 0
# use while loop to iterate until zero
while(num > 0) {
sum = sum + num
num = num - 1
}
print(paste("The sum is",sum))
}
Output
Enter a number: 10 [1] "The sum is 55"
Here, we ask the user for a number and display the sum of natural numbers upto that number. We use while
loop to iterate until the number becomes zero.
We could have solved the above problem without using any loops. From mathematics, we know that sum of natural numbers is given by n*(n+1)/2. We could have used this formula directly. For example, if n = 10, the sum would be (10*11)/2 = 55.